package com.sky.task;

import com.alibaba.fastjson.JSON;
import com.sky.mapper.user.OrderMapper;
import com.sky.pojo.Orders;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
//@Component
public class OrderPayCheckTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private Config config;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkOrderPayCheckTask() {
        log.info("检查支付超时订单任务开始");
        //去数据库中找处于待支付的订单 15分钟前的订单
        LocalDateTime before15Min = LocalDateTime.now().minusMinutes(15);
        List<Orders> checkPayStatusOrders = orderMapper.getCheckPayStatusOrders(before15Min);

        if (CollectionUtils.isEmpty(checkPayStatusOrders)) {
            log.info("没有要处理的订单");
            return;
        }

        for (Orders checkPayStatusOrder : checkPayStatusOrders) {
            Boolean flag = getPayStatusFromWX(checkPayStatusOrder.getNumber());
            if (flag){
                checkPayStatusOrder.setStatus(Orders.TO_BE_CONFIRMED);
                checkPayStatusOrder.setPayStatus(Orders.PAID);
                orderMapper.updateOrderPaySuccess(checkPayStatusOrder);
            }else {
                checkPayStatusOrder.setStatus(Orders.CANCELLED_ORDER);
                checkPayStatusOrder.setCancelTime(LocalDateTime.now());
                checkPayStatusOrder.setCancelReason("超时未支付");
                orderMapper.cancelOrder(checkPayStatusOrder);
            }

        }
    }

    public Boolean getPayStatusFromWX(String orderNo) {
        try {
            QueryOrderByOutTradeNoRequest orderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
            orderByOutTradeNoRequest.setMchid("1561414331");
            orderByOutTradeNoRequest.setOutTradeNo(orderNo);

            // 构建service
            NativePayService service = new NativePayService.Builder().config(config).build();
            Transaction result = service.queryOrderByOutTradeNo(orderByOutTradeNoRequest);
            if (result.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)){
                return true;
            }
        } catch (ServiceException e) {
            if (e.getErrorCode().equals("ORDER_NOT_EXIST")){
                log.info("微信订单不存在，没有发起过支付");
                return false;
            }
        }
        return false;
    }
}
